/*
 * @Descripttion: 
 * @version: 
 * @Author: panle
 * @Date: 2020-04-14 15:16:00
 * @LastEditors: panle
 * @LastEditTime: 2020-08-10 15:04:06
 */
import { TextEncoder } from 'Text-encoding'; 

import {
  PublishtionModel
} from './publishtion.js'

const tips = {
  0: '正常',
  10000: '未初始化蓝牙适配器',
  10001: '蓝牙可能被关闭,请打开手机蓝牙后重试',
  10002: '没有找到指定设备',
  10003: '连接失败',
  10004: '没有找到指定服务',
  10005: '没有找到指定特征值',
  10006: '当前连接已断开',
  10007: '当前特征值不支持此操作',
  10008: '其余所有系统上报的异常',
  10009: 'Android 系统特有，系统版本低于 4.3 不支持 BLE',
  10012: '连接超时',
  10013: '连接 deviceId 为空或者是格式不正确',
  20000: '蓝牙适配器不可用，蓝牙可能被关闭',
}
// 搜索设备名称
const driveOptions = [
  'SHAPE_520','SHAPE_520X', 'Bodecoder_CHL818', 'Bodecoder_CHL81','Bodecoder_CHL81%01','BDE_WEIXIN_TTM',
  'Bodecoder_CHL818S','Bodecoder_CHL618','BDR_PE6','BDR_PE6S',
  'BDR_FE10','BDR_SE208',
  'SE208-T01','SE208-T02','SE208-T03','SE208-T04',
  'SE208-T05','SE208-T06','SE208-T07','SE208-T08',
  'F7','BDR_CHL818_Plus','BDR_SE208P',
  "Bodecoder_diving1",
  "Bodecoder_diving2",
  "Bodecoder_diving3",
  "Bodecoder_diving3A",
  "Bodecoder_diving4",
  "Bodecoder_diving5",
  "Bodecoder_diving6",
  "Bodecoder_diving7",
  "Bodecoder_diving8",
  "Bodecoder_diving9",
  "Bodecoder_diving10",
  "Bodecoder_diving11",
  "Bodecoder_diving12",
  "Bodecoder_diving13",
  "Bodecoder_diving14",
  "Bodecoder_diving15",
  "Bodecoder_diving16",
  "Bodecoder_diving17",
  "Bodecoder_diving18",
  "Bodecoder_diving19",
  "Bodecoder_diving20",
  "Bodecoder_diving21",
  //
  "Bodecoder_diving1s",
  "Bodecoder_diving2s",
  //
  "sporter_01",
  "sporter_02",
  "sporter_03"
]
var getConnectedTimer = ''
var serviceParams = {}
class BluetoothMode extends PublishtionModel {

  //获取搜索到的蓝牙设备
  data = []

  //初始化蓝牙适配器
  initBluetooth(fn,fn2,fn3) {
    return new Promise((resolve, reject) => {
      this._initBluetooth(fn2).then(res => {
        resolve(res)
        this._getBluetoothState()
        return this._search()
      }).then(res => {
        // 开启监听 
        this._onDFound(()=>{
          fn3&&fn3()
        })
        resolve(res)
      }).catch(errs=>{
        fn&&fn(errs,111)
      })
    })
  }

    //F7初始化蓝牙适配器
  initBluetoothF7(serviceId){
    return new Promise((resolve, reject) => {
      this._initBluetooth().then(res => {
        this._getBluetoothState()
        return this._searchF7(serviceId)
      }).then(res => {
        // 开启监听 
        // this._onDFoundF7(serviceId)
        resolve(res)
      })
    })
  }

  _initBluetooth(fn2) {
    return new Promise((resolve, reject) => {
      // wx.openBluetoothadapter({
      //   success(res){
      //     wx.getSetting({
      //       success(res){
      //         console.log(res.authSetting);
      //         if(res.authSetting.hasOwnProperty('scope.bluetooth')){
      //           if(!res.authSetting['scope.bluetooth']){
      //             wx.openSetting({
      //               success(res){
      //                 resolve
      //               }
      //             })
      //           }
      //         }else{
      //           wx.authorize({
      //             scope:'scope.bluetooth',
      //             success(){
      //               resolve()
      //             }
      //           })
      //         }
      //       }
      //     })
      //   }
      // })
      wx.openBluetoothAdapter({
        success: res => {
          fn2&&fn2('none')
          console.log(res)
          console.log('初始化蓝牙模块成功')
          resolve()
        },
        fail: error => {
          fn2&&fn2(error)
          console.log("111"+error.errCode)
          resolve(error.errCode)
          // this._showTips(error.errCode)
        }
      })
    })
  }

  // 连接低功耗蓝牙
  connection(deviceId,cb) {
    return new Promise((resolve, reject) => {
      wx.createBLEConnection({//连接
        deviceId,
        timeout:10000,
        success: res => {
          console.log("createBLEConnection++连接蓝牙成功"+res)
          this._setDevice(deviceId)
          // 暂停搜索
          this.stop()
          resolve({
            res,
            deviceId
          })
        },
        fail: res => {
          console.log(res)
          cb&&cb(res)
        },
      })
    })
  }

  connect(deviceId,cb) {
    
    return new Promise((resolve, reject) => {
      this.connection(deviceId,cb).then(res => {
        
        return this.getServiceList(res.deviceId)//获取服务
      }).then(res => {
        let promiseList = []
        for (var i in res.services) {
          promiseList.push(this.getBLEDeviveChar({//获取value读写交互
            deviceId,
            serviceId: res.services[i].uuid
          }))
        }
       
        return Promise.all(promiseList)
      }).then(res => {
    
        resolve(this.serviceParams)
      })
    })
  }

  // 启用低功耗蓝牙设备特征值变化时的 notify 功能，订阅特征值。
  // 注意：必须设备的特征值支持 notify 或者 indicate 才可以成功调用。
  notify({
    deviceId,
    serviceId,
    characteristicId
  }) {
    return new Promise((resolve, reject) => {
      wx.notifyBLECharacteristicValueChange({
        state: true, // 启用 notify 功能
        // 这里的 deviceId 需要已经通过 createBLEConnection 与对应设备建立链接
        deviceId,
        // 这里的 serviceId 需要在 getBLEDeviceServices 接口中获取
        serviceId,
        // 这里的 characteristicId 需要在 getBLEDeviceCharacteristics 接口中获取
        characteristicId,
        success(res) {
          resolve(res)
          console.log('notifyBLECharacteristicValueChange success', res.errMsg)
        }
      })
    })
  }

  writeNotify(params){
    return new Promise(res =>{
        this.write({//获取value读写交互
          deviceId: params.deviceId,
          serviceId: params.serviceId,
          characteristicId: params.uuid,
          value:params.value,
          status:params.status,
        }).then(res =>{
          return this.onNotifyChange(params.status)
        }).then(res =>{
          resolve(res)
        })
    })
  }
  
  // 获取服务列表
  getServiceList(deviceId) {
    return new Promise((resolve, reject) => {
      wx.getBLEDeviceServices({
        // 这里的 deviceId 需要已经通过 createBLEConnection 与对应设备建立链接
        deviceId,
        success(res) {
          console.log('device services:', res.services)
          resolve({
            services: res.services,
            deviceId
          })
        }
      })
    })
  }

  // 获取蓝牙设备某个服务中所有特征值 getBLEDeviceCharacteristics
  getBLEDeviveChar({
    deviceId,
    serviceId
  }) {
    return new Promise((resolve, reject) => {
      const that = this
      wx.getBLEDeviceCharacteristics({
        // 这里的 deviceId 需要已经通过 createBLEConnection 与对应设备建立链接
        deviceId,
        // 这里的 serviceId 需要在 getBLEDeviceServices 接口中获取
        serviceId,
        success(res) {
          resolve(res)
          for (var i = 0; i < res.characteristics.length; i++) {//2个值
            var model = res.characteristics[i]
            var uuid = model.uuid.substring(4, 8)   
            var params = {}    
            if (model.properties.notify == true && uuid === 'FFB2') { //‘FFB2’为设备定义的读写UUID
              
              params.deviceId = deviceId
              params.serviceId = serviceId
              params.uuid = model.uuid  
              that.serviceParams = params
              that.startNotice(deviceId,serviceId,model.uuid);
            }
          }
          console.log('device getBLEDeviceCharacteristics:', res.characteristics)
        }
      })
    })
  }

  // 断开与低功耗蓝牙设备的连接。
  closeConnection(deviceId) {

    wx.closeBLEConnection({
      deviceId,
      success(res) {
        console.log(res+"closeBLEConnection")
      }
    })
  }

  //向低功耗蓝牙设备特征值中写入二进制数据。
  write({
    deviceId,
    serviceId,
    characteristicId,
    value
  }) {
    console.log("value"+value)
    //传入array 返回 ArrayBuffer类型
    let bufferstr = this._hexStringToArrayBuffer(value)
    return new Promise((resolve, reject) => {
      var length = bufferstr.byteLength;
      var count = Math.ceil(length/20);
      for(var i=0;i<count;i++){
        //对buffer进行分包，最大不超过20字节
        let tempBuffer;
        if(((i+1)*20)<length){
          tempBuffer = bufferstr.slice(i*20,(i+1)*20);
        }else{
          tempBuffer = bufferstr.slice(i*20,length);
        }
        this.Delayed(200).then( ()=>{ //延迟200ms
          //写入设备
          wx.writeBLECharacteristicValue({
            deviceId,
            serviceId,
            characteristicId,
            value: tempBuffer, //写入数据
            success: function (res) {
              console.log('2022-7-27',res.errMsg)
              console.log('--多包writeBLECharacteristicValue success',res.errMsg)
              resolve(res)
            },
            fail: function (res) {
              console.log('发送失败',res.errMsg)
              reject()
            },
          })
        } )

      }
    })
  }
  writeSp({
    deviceId,
    serviceId,
    characteristicId,
    value
  }) {
    console.log("value"+value)
    //传入array 返回 ArrayBuffer类型
    var bufferstr = this._hexStringToArrayBuffer(value)

    var systemInfo = {}
    var an = {}
    wx.getSystemInfo({
      success: function (res) {
          systemInfo = res
      }
    })
    // if(systemInfo.platform == "android"){
    //   an = bufferstr.slice(0,20)
    // }

    // var that = this
    // let e = value
    // var values = systemInfo.platform == "android" ? an : bufferstr

    // console.log("values======"+values)
      return new Promise((resolve, reject) => {
        wx.writeBLECharacteristicValue({
      
          deviceId,
          // 这里的 serviceId 需要在 getBLEDeviceServices 接口中获取
          serviceId,
          // 这里的 characteristicId 需要在 getBLEDeviceCharacteristics 接口中获取
          characteristicId,
          // 这里的value是ArrayBuffer类型
  
          value: bufferstr,
          success(res) {
            resolve(res)
            console.log('writeBLECharacteristicValue success', res.errMsg)
            console.log("characteristicId"+res)
            console.log('数据发送成功')
            console.log("writeSp"+systemInfo.platform)
            if(systemInfo.platform == "ios"){


            }else if(systemInfo.platform == "android"){

              var str = bufferstr.slice(20,bufferstr.length) //.slice(20,bufferstr.length)
              console.log("androidvalues======"+str)
              var timeTer = setTimeout(() => {
                  wx.writeBLECharacteristicValue({
                    deviceId,
                    // 这里的 serviceId 需要在 getBLEDeviceServices 接口中获取
                    serviceId,
                    // 这里的 characteristicId 需要在 getBLEDeviceCharacteristics 接口中获取
                    characteristicId,
                    // 这里的value是ArrayBuffer类型
                    value: str,
                    success(res) {
                      clearTimeout(timeTer)
                      resolve(res)
                      console.log('数据发送成功2')
                    }
                  })
              }, 1000);
 
            }
            // wx.readBLECharacteristicValue({
            //   deviceId: deviceId,
            //   serviceId:serviceId,
            //   characteristicId:characteristicId,
            //   success: function (res) {
            //     console.log('读取数据成功')
            //     console.log(res)
            //   },
            //   fail: function (res){
            //     console.log(res)
            //     wx.showToast({
            //       title: res.errMsg,
            //       icon: 'none',
            //       duration: 1500
            //     })
            //   }
            // })
          },
          fail: function (res) {
            console.log('发送失败', res)
            wx.showToast({
              title: res.errMsg,
              icon: 'none',
              duration: 1500
            })
          }
        })
      })


  }
  Delayed(ms,callback) {
    return new Promise(function(Resolve,Peject){
      setTimeout(function(){
        Resolve(callback);
      },ms);
    })
  }
  sleep(numberMillis) {
    var now = new Date();
    var exitTime = now.getTime() + numberMillis;
    while (true) {
      now = new Date();
      if (now.getTime() > exitTime)
        return;
    }
  }

  delay(ms, res) {
    return new Promise(function(resolve, reject) {
        setTimeout(function() {
            resolve(res);
        }, ms);

    });
  }
  // 停止搜寻附近的蓝牙外围设备
  stop() {
    return new Promise((resolve, reject) => {
      wx.stopBluetoothDevicesDiscovery({
        success(res) {
          console.log(res)
          resolve(res)
        }
      })
    })

  }

  // 关闭蓝牙适配器
  close() {
    //关闭当前的蓝牙模块 
    wx.closeBluetoothAdapter({ 
        success: (res) => {
            console.log("关闭蓝牙模块成功", res);
        }, 
        fail: (err) => {
          console.log("关闭蓝牙模块出错", err); 
        },
        complete: (res) => { 
          console.log("关闭蓝牙模块完成的", res); // ignore
        },   
    });

  }

  // 获取设备Id
  getDevice() {
    return wx.getStorageSync('deviceId')
  }
  // 开启蓝牙搜索
  _searchF7(serviceId) {
    // wx.showLoading({
    //   title: '正在扫描中...',
    // })
    return new Promise((resolve, reject) => {
      wx.startBluetoothDevicesDiscovery({
        powerLevel: "high",
        // services: [serviceId], // 用来过滤掉其他蓝牙设备
        success: res => {
          console.log(res)
          resolve(res)
        },
        fail: err => {
          console.log(err)
        },
        complete: res => {
          // setTimeout(() => {
          //   wx.hideLoading()
          // }, 2000)
        }
      })
    })
  }
  // 开启蓝牙搜索
  _search() {
    // wx.showLoading({
    //   title: '正在扫描中...',
    // })
    return new Promise((resolve, reject) => {
      wx.startBluetoothDevicesDiscovery({
        powerLevel: "high",
        // services: ['SHAPE_520X','Bodecoder_CHL618','Bodecoder_CHL818','Bodecoder_CHL818','BDR_CHL818_Plus'], // 用来过滤掉其他蓝牙设备
        success: res => {
          console.log(res)
          resolve(res)
        },
        fail: err => {
          reject(err)
        },
        complete: res => {
          // setTimeout(() => {
          //   wx.hideLoading()
          // }, 2000)
        }
      })
    })
  }

  //手动开启搜索
  _handlersearch(fn3){
    return new Promise((resolve, reject) => {
      return this._search()
    }).then(res => {
      // 开启监听 
      this._onDFound(()=>{
        fn3&&fn3()
      })
      resolve(res)
    }).catch(errs=>{
      fn&&fn(errs,111)
    })
  }

  //初始化蓝牙适配器
  getConnectedBlue(serviceId) {
    return new Promise((resolve, reject) => {
      this._initBluetooth().then(res => {
        this._getBluetoothState()
        return this._search()
      }).then(res => {
        // 开启监听 
        this.getConnectedBluetoothDevices(serviceId)
        resolve(res)
      })
    })
  }
  getConnectedBluetoothDevices(serviceId) {
    var that = this;
    var flag = false
    var deviceId = ''
    wx.getConnectedBluetoothDevices({
      services: [serviceId],
      success: function (res) {
      console.log("获取处于连接状态的设备", res);
      var devices = res['devices'], 
      flag = false, 
      index = 0, 
      conDevList = [];
      devices.forEach(function (value, index, array) {
    
      if (driveOptions.indexOf(value['name']) != -1 && serviceId == value['deviceId']) {
          // 如果存在包含FeiZhi字段的设备
          flag = true;
          index += 1;
          conDevList.push(value['deviceId']);
          that.deviceId = value['deviceId'];
          return;
      }
    
    });
    
    if (flag) {
      this.connectDeviceIndex = 0;
      that.connect(conDevList);
    } else {
    
    if (!getConnectedTimer) {
      getConnectedTimer = setTimeout(function () {
         that.getConnectedBluetoothDevices();
      }, 5000);
    }
  }
  },
  fail: function (err) {  
      if (!getConnectedTimer) {
        getConnectedTimer = setTimeout(function () {
          that.getConnectedBluetoothDevices();
        }, 5000);
      } 
    } 
  });
}
  arrayStringToArrayBuffer(array){
    if(array.length <= 0){
      return new ArrayBuffer(0);
    }
    var buffer = []
    for(var i = 0; i < array.length; i++){
      buffer[i] = this.hex_to_bin(array[i])
    }
    return this._hexStringToArrayBuffer(buffer)
  }
  
  //返回ArrayBuffe
  _hexStringToArrayBuffer(str) {
    let val = ""
    if (!str) {
      return new ArrayBuffer(0);
    }
    var buffer = new ArrayBuffer(str.length);
    let dataView = new DataView(buffer)
    let ind = 0;
    for (var i = 0, len = str.length; i < len;  i ++) {
      // let code = parseInt(str.substr(i, 2), 16)
      dataView.setUint8(ind, str[i])
      // dataView.setInt16(ind, str[i])
      ind++
    }
    return buffer;

     
  }
  hex_to_bin(str) {            
    let hex_array = [{key:0,val:"0000"},{key:1,val:"0001"},{key:2,val:"0010"},{key:3,val:"0011"},
    {key:4,val:"0100"},{key:5,val:"0101"},{key:6,val:"0110"},{key:7,val:"0111"},                
    {key:8,val:"1000"},{key:9,val:"1001"},{key:'a',val:"1010"},{key:'b',val:"1011"},{key:'c',val:"1100"},
    {key:'d',val:"1101"},{key:'e',val:"1110"},{key:'f',val:"1111"}]             
    let value=""            
    for(let i=0;i<str.length;i++){                
      for(let j=0;j<hex_array.length;j++){                   
         if(str.charAt(i).toLowerCase()== hex_array[j].key){                        
           value = value.concat(hex_array[j].val)                        
           break                    
          }                
        }            
      }            
      console.log(value)           
       return value        
    }
  // 开启监听获取到新的设备
  _onDFound(fn) {
      var foundflags = null
      wx.onBluetoothDeviceFound(devices =>{
        // console.log('onBluetoothDeviceFound',devices)
        //
        clearTimeout(foundflags)
        this._getDevices().then(res=>{
          // console.log(this,1314)
          this.publish(this.data,'newDevice')
        })
        // console.dir(devices)
      })
      foundflags = setTimeout(()=>{
        fn&fn()
      },10000)
    }
  // 获取寻找的所有设备
  _getDevices() {
    return new Promise((resolve, reject) => {
      wx.getBluetoothDevices({
        success: res => {
          var temparr = []
          for(var i = 0;i<res.devices.length;i++){
            temparr.push(res.devices[i].localName || res.devices[i].name)
          }
          // console.log('搜到设备：'+temparr.join('，'))
          //
          var systemInfo = wx.getStorageSync('systemInfo')
          var d = systemInfo.system.split(' ')
          var serviceId = d[0] == "iOS" ? '00001A20-0000-1000-8000-00805F9B34FB' : '33:44:55:66:77:88'
          var array = []
          for (var x in res.devices) {
            // var _encoder = new TextEncoder("utf-8", {NONSTANDARD_allowLegacyEncoding: true});
            // // content 需要打印的字符串
            // const val = _encoder.encode(res.devices[x].name);
            // console.log(encodeURIComponent(res.devices[x].name))
            if ((res.devices[x].name != '未知设备' || res.devices[x].localName != '未知设备')
              && res.devices[x].advertisData 
              && (driveOptions.indexOf(encodeURIComponent(res.devices[x].name)) >= 0 || driveOptions.indexOf(encodeURIComponent(res.devices[x].localName)) >= 0)) {
              res.devices[x].advertisData = this._ab2hex(res.devices[x].advertisData)
              //  res.devices[x].advertisData = this._ab2hex(res.devices[x])
              array.push(res.devices[x])
            }else if ((res.devices[x].advertisServiceUUIDs && res.devices[x].advertisServiceUUIDs == serviceId) || (res.devices[x].deviceId && res.devices[x].deviceId == serviceId) && res.devices[x].advertisData){
              res.devices[x].name = 'F7'
              var advertisData = this._ab2hex(res.devices[x].advertisData)
              res.devices[x].advertisData = advertisData
              array.push(res.devices[x])
            }
          }
          // console.log(array)
          this.data = array
          resolve(array)
        }
      })
    })
  }

  // 获取蓝牙适配器的状态
  _getBluetoothState() {
    const that = this
    wx.onBluetoothAdapterStateChange(res => {
      // console.log(res,111)
      if (res.available) {
        console.log('蓝牙模块可用')
      } else {
        wx.showModal({
          title: '提示',
          content: '蓝牙已被关闭',
          showCancel: false,
          success(res) {
            if (res.confirm) {
              console.log('用户点击确定')
            } else if (res.cancel) {
              console.log('用户点击取消')
            }
          }
        })
        // this._showTips(20000)
        console.log('蓝牙模块不可用')
      }
      if (res.discovering) {
        console.log('蓝牙适配器处于搜索状态')
      } else {
        console.log('蓝牙适配器不处于搜索状态')
      }
    })
  }
  
  startNotice(deviceId,serviceId,uuid){
    var that = this;
    wx.notifyBLECharacteristicValueChange({
      state: true, // 启用 notify 功能
      // 这里的 deviceId 需要已经通过 createBLEConnection 与对应设备建立链接 
      deviceId: deviceId,
      // 这里的 serviceId 需要在上面的 getBLEDeviceServices 接口中获取
      serviceId: serviceId,
      // 这里的 characteristicId 需要在上面的 getBLEDeviceCharacteristics 接口中获取
      characteristicId: uuid,  //第一步 开启监听 notityid  第二步发送指令 write
      success: function (res) {
        console.log("notifyUuid"+uuid)
      // 设备返回的方法
          console.log("notifyBLECharacteristicValueChange"+res.errMsg)

      }
    })
}

  // ArrayBuffer转16进度字符串示例
  _ab2hex(buffer) {
    var array = []
    var dv = new DataView(buffer);
    for(var i=0;i<dv.byteLength;i++){ 
       var data = dv.getUint8(i);
       array[i] = this.int2hex(data,2) 
    }
    if(array.length > 0){
        var notifyValue = wx.getStorageSync('notifyValue')
        // console.log("notifyValue++"+notifyValue)
        notifyValue =notifyValue && notifyValue.length > 0 ? notifyValue.concat(array) : array    
        wx.setStorageSync('notifyValue', notifyValue)
      
    }else{
      wx.getStorageSync('notifyValue') && wx.clearStorage('notifyValue')
    }
    // console.log("array-----"+array)
    return array;
  }
  sendStartValue(stastu){
    var params = []
    var m = "0x"
    params[0] = stastu.substring(0,4)
    params[1] = m.concat(stastu.slice(4))
    return params
  }
  // 错误提示
  _showTips(code) {
    code && wx.showModal({

      title: '提示',

      content: tips[code],
      showCancel: false,
      success: function (res) {
        if (res.confirm) {
          if(code == 10001){
            wx.navigateBack()
          }
            console.log('用户点击确定')
        }else{
            console.log('用户点击取消')
        }
      }

  })
    // code && wx.showToast({
      
    //   title: tips[code],
    //   icon: 'none'
    // })
  }

  // 储存设备Id
  _setDevice(id) {
    wx.setStorageSync('deviceId', id)
  }

  stringBufferValue(array){
    if(array.length > 0) {
      var value = 0
      for(var i = 0; i < array.length; i++) {
          var data = array[i].substring(2,4)
        //  value += data.toString(16)
          var sendMy =  this.hex2int(data)
          value += sendMy
      }
      
      // value = value + ""
      // if(value.length > 2){
      //   value = value.slice(4)
      // }
      // value = parseInt(value)
      var arrLast = this.int2hex(value,2) 
      if(arrLast.length > 4){
        arrLast = arrLast.substring(arrLast.length-2)
        arrLast = "0x"+arrLast
      }
      array[array.length] = arrLast  //arrLast.substring(0,4)
   }
   return array
  }
   hex2int(hex) {
    var len = hex.length, a = new Array(len), code;
    for (var i = 0; i < len; i++) {
        code = hex.charCodeAt(i);
        if (48<=code && code < 58) {
            code -= 48;
        } else {
            code = (code & 0xdf) - 65 + 10;
        }
        a[i] = code;
    }
     
    return a.reduce(function(acc, c) {
        acc = 16 * acc + c;
        return acc;
    }, 0);
}
 int2hex(num, width,type) {//十六进制
  var hex = "0123456789abcdef";
  var s = "";
  while (num) {
    s = hex.charAt(num % 16) + s;
    num = Math.floor(num / 16);
  }
  if (typeof width === "undefined" || width <= s.length) {
    return "0x" + s;
  }
  var delta = width - s.length;
  var padding = "";
  while(delta-- > 0) {
    padding += "0";
  }
  return "0x" + padding + s;
}
  subMethod(array){
    var arrayPrams = []
    for (var i = 0; i < array.length; i++) {
      arrayPrams[i]=array[i].substring(2,4)
    }
    return arrayPrams
  }
}

export {
  BluetoothMode
}